package com.ocean.linkedlist;

/**
 * https://leetcode.cn/problems/merge-two-sorted-lists/
 */
public class MergeTwoSortedLists2 {

    public static void main(String[] args) {
        ListNode e5 = new ListNode(5, null);
        ListNode e4 = new ListNode(4, e5);
        ListNode e3 = new ListNode(3, e4);
        ListNode e2 = new ListNode(2, e3);
        ListNode e1 = new ListNode(1, e2);


//        ListNode e55 = new ListNode(5, null);
//        ListNode e44 = new ListNode(4, e55);
//        ListNode e33 = new ListNode(3, e44);
        ListNode e22 = new ListNode(2, null);
        ListNode e11 = new ListNode(1, e22);

        ListNode listNode = new MergeTwoSortedLists2().mergeTwoLists(e1, e11);
        ListNode.print(listNode);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode dummy = new ListNode();
        ListNode pre = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                pre.next = l1;
                pre = l1;
                l1 = l1.next;
            } else {
                pre.next = l2;
                pre = l2;
                l2 = l2.next;
            }
        }
        pre.next = l1 == null ? l2 : l1;
        return dummy.next;
    }

}
